from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import redirect
from django.conf import settings
import datetime

"""
中间件的流程:
    1.request请求到来执行所有的process_request
    2.路由
    3.执行process_view
    4...
"""


class Tracer(object):

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """如果用户已登录，在request赋值"""
        # # ### request.tracer 用户信息 ###
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object
        # 白名单:没有登录都可以访问的url
        """
        1.获取当用户访问的URL
        2.检查URL中是否在白名单中
        """
        # 获取当前访问的URL
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return  # 中间件中return表示None
        # 检查用户是否登录，已登录继续；否则返回登录页面
        if not request.tracer.user:
            return redirect("login")
        # 登陆成功之后访问后台管理时才能拿到额度
        # 获取当前用户的额度

        # ### 额度信息存储在request中 ###
        # 方式一:免费的额度在交易记录中存储
        # 获取当前用户ID值最大的(最近的交易记录)
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        # 判断是否过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            # 过期
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()
        # 将最近一次的交易记录存储在request
        # request.transaction = _object
        # request.price_policy 价格策略
        request.tracer.price_policy = _object.price_policy

        """
        # 方式二:免费的额度存储在配置文件中
        # 获取当前用户ID值最大的(最近的交易记录)
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        if not _object:
            # 没有购买
            request.price_policy = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
        else:
            # 付费版
            current_datetime = datetime.datetime.now()
            if _object.end_datetime and _object.end_datetime < current_datetime:
                # 过期
                request.price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
            else:
                request.price_policy = _object.price_policy
        """

    def process_view(self, request, view, args, kwargs):

        # 判断URL是否是以manage开头，如果是则判断项目ID是否是我创建 or 参与
        if not request.path_info.startswith('/web/manage/'):
            return

        project_id = kwargs.get('project_id')
        # 是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()

        if project_object:
            # 是我创建的项目的话，我就让他通过
            request.tracer.project = project_object
            return
        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return
        return redirect('project_list')
    # def process_view(self, request, view, args, kwargs):
    #
    #     # 判断url是否manage开头,如果是则判断项目ID是否是我创建的or参与的
    #     if not request.path_info.startswith('/manage/'):
    #         return
    #     project_id = kwargs.get('project_id')
    #     # 判断项目是否是自己的project_id是否是我创建的或者我参与的
    #     project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id, ).first()
    #     if project_object:
    #         # 是我创建的,就通过
    #         # 当前项目信息封装到tracer中
    #         request.tracer.project = project_object
    #         return
    #
    #     # 是否是我参与的项目
    #     project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
    #     if project_user_object:
    #         # 是我参与的
    #         # 当前项目信息封装到tracer中
    #         request.tracer.project = project_user_object.project
    #         return
    #
    #     # 是manage开头但是不是我参与的也不是我创建的
    #     return redirect('project_list')
